#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/alias.sh"

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"

APP_TARGET_DIR_NAME="minimax-remover"

export CURRENT_APP_PATH="$LMD_APPS_DIR/$APP_TARGET_DIR_NAME"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

cd "$CURRENT_APP_PATH"
conda --version

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

export GRADIO_TEMP_DIR="./temp_gradio"
CONDA_PREFIX="../venv"

export HF_HOME="./tmp_hf_home"
export TORCH_HOME="./tmp_torch_home"
export GRADIO_TEMP_DIR="./gradio_temp"

cd "$CURRENT_APP_PATH/gradio_demo"

echo "LMD_LAUNCH_APP_MODULE : ${LMD_LAUNCH_APP_MODULE}"

if [ "$LMD_LAUNCH_APP_MODULE" = "image" ]; then
    echo "launch image object remover"
    rm -rf image_demo_temp1.py image_demo_temp2.py
    sed '/demo\.launch/s/^/# /' image_demo.py > image_demo_temp1.py
    sed -i '$a demo.launch()' image_demo_temp1.py
    sed 's|/tmp/|./gradio_temp/|g' image_demo_temp1.py > image_demo_temp2.py
    conda run -p "$CONDA_PREFIX" --no-capture-output python image_demo_temp2.py
else
    echo "launch video object remover"
    rm -rf test_temp1.py test_temp2.py
    sed '/demo\.launch/s/^/# /' test.py > test_temp1.py
    sed -i '$a demo.launch()' test_temp1.py
    sed 's|/tmp/|./gradio_temp/|g' test_temp1.py > test_temp2.py
    conda run -p "$CONDA_PREFIX" --no-capture-output python test_temp2.py
fi
